package cn.skyisazure.metacompare.sqlcompare.meta;

import cn.skyisazure.metacompare.metaVo.DataSourceTypeEnum;
import cn.skyisazure.metacompare.metaVo.EntityDataSourceInfoVO;
import cn.skyisazure.metacompare.metaVo.EntityTableInfoVO;
import cn.skyisazure.metacompare.metaVo.MetaColumnRespVO;
import cn.skyisazure.metacompare.sqlcompare.utils.DBTypeConvert;
import lombok.Data;
import lombok.NonNull;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangjj
 * @date 2023/8/21 17:35
 */
@Data
@Accessors(chain = true)
public class TableCM {

    /** 元数据唯一ID */
    private Serializable id;

    /**数据库名*/
    private String dsName;

    /**数据库id*/
    private String dsId;

    /** 表名 */
    private String name;

    /** 创建表时字段信息 */
    private List<ColumnCM> columns;

    /**改表名时使用，旧表名*/
    private String oldName;

    public static TableCM build(@NonNull EntityTableInfoVO tableInfoVO,
                                @NonNull DBTypeConvert dbTypeConvert,
                                @NonNull EntityDataSourceInfoVO entityDataSourceInfoVO){
        TableCM table = new TableCM();
        table.setId(tableInfoVO.getMetaTable().getQueryKey());
        table.setDsName(entityDataSourceInfoVO.getCode());
        table.setDsId(entityDataSourceInfoVO.getQueryKey());
        table.setName(tableInfoVO.getMetaTable().getCode());
        // 列
        List<MetaColumnRespVO> fields = tableInfoVO.getFields()
                .stream()
                // .filter(field -> ArrayUtil.contains(new MysqlColumnType[]{MysqlColumnType.FORMULA,MysqlColumnType.RELATION}, field.getType()))
                .sorted(Comparator.comparing(MetaColumnRespVO::getSort)).collect(Collectors.toList());
        List<ColumnCM> columns = new ArrayList<>();
        for (MetaColumnRespVO field : fields) {
            ColumnCM column = ColumnCM.build(field,
                    dbTypeConvert,
                    tableInfoVO);
            columns.add(column);
        }
        table.setColumns(columns);
        return table;
    }
}
